package Controller.member;

import java.io.IOException;

import Services.WebService;

import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Entity.Book;
import Entity.BookInvoice;
import Entity.Invoice;

public class PurchaseRecordServlet extends MemberBaseServlet {    
    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response, WebService webServices, String action) throws ServletException, IOException {
    	if(action != null){
    		request.setAttribute("action", action);
    		
    		if(action.equals("refund")){
    			makeRefundRequest(request,response,webServices,action);
    		}
    		else if(action.equals("cancel")){
    			cancelRefundRequest(request,response,webServices,action);
    		}
    	}
    	else {
    		request.setAttribute("action", "list");
    		showRecord(request,response,webServices,action);
    	}
    }
    
    private void showRecord(HttpServletRequest request, HttpServletResponse response, WebService webServices, String action){
    	ArrayList<Invoice> invoiceList = webServices.getEntityManager().getInvoices(webServices.getCurrentUser().getId());
    	ArrayList<Book> bookList = new ArrayList<Book>();
    	
    	for(int i=0;i<invoiceList.size();i++){
    		bookList.add(webServices.getEntityManager().getBookFromInvoice(invoiceList.get(i).getId()));
    	}
    	
    	request.setAttribute("bookList", bookList);
    	request.setAttribute("invoiceList", invoiceList);
    	this.forward(request, response, webServices, action, "/member/member.purchaseHistory.jsp");
    }
    
    private void makeRefundRequest(HttpServletRequest request, HttpServletResponse response, WebService webServices, String action){
    	Invoice invoice = webServices.getEntityManager().getInvoice(Integer.valueOf(request.getParameter("id")));
    	invoice.setRefund(true);
    	
    	webServices.getEntityManager().updateInvoice(invoice);
    	
    	request.setAttribute("request_invoice", invoice);
    	showRecord(request,response,webServices,action);
    }
    
    private void cancelRefundRequest(HttpServletRequest request, HttpServletResponse response, WebService webServices, String action){
    	Invoice invoice = webServices.getEntityManager().getInvoice(Integer.valueOf(request.getParameter("id")));
    	invoice.setRefund(false);
    	
    	webServices.getEntityManager().updateInvoice(invoice);
    	
    	request.setAttribute("request_invoice", invoice);
    	showRecord(request,response,webServices,action);
    }
}